import {app, BrowserWindow, Menu} from 'electron'
import {platform} from "os"
import menuconfig from '../config/menu'
import {openDevTools} from '../config/const'
import setIpc from './ipcMain'
import {winURL} from '../config/StaticPath'

import messageService from './messageService'


var mainWindow = null
//调用ipcMain中的方法
setIpc.Mainfunc()

function createMainWindow() {
    /**
     * Initial window options
     */
    mainWindow = new BrowserWindow({
        height: 600,
        useContentSize: true,
        width: 1200,
        minWidth: 800,
        show: false,
        frame: true,
        titleBarStyle: platform().includes('win32') ? 'default' : 'hidden',
        webPreferences: {
            contextIsolation: false,
            nodeIntegration: true,
            webSecurity: false,
            // 如果是开发模式可以使用devTools
            devTools: process.env.NODE_ENV === 'development' || openDevTools,
            // devTools: true,
            // 在macos中启用橡皮动画
            scrollBounce: process.platform === 'darwin'
        }
    })
    // 这里设置只有开发环境才注入显示开发者模式
    if (process.env.NODE_ENV === 'development' || openDevTools) {
        menuconfig.push({
            label: '开发者设置',
            submenu: [{
                label: '切换到开发者模式',
                accelerator: 'CmdOrCtrl+I',
                role: 'toggledevtools'
            }]
        })
    }
    // 载入菜单(我手动改为[],如果将[]改为menuconfig,则会显示自定义菜单
    const menu = Menu.buildFromTemplate([])
    Menu.setApplicationMenu(menu)

    //手动让window来加载静态资源路径下的内容
    mainWindow.loadURL(winURL)


    mainWindow.webContents.once('dom-ready', () => {
        mainWindow.show()
        if (process.env.NODE_ENV === 'development' || openDevTools) mainWindow.webContents.openDevTools(true)
    })
    mainWindow.on('maximize', () => {
        mainWindow.webContents.send("w-max", true)
    })
    mainWindow.on('unmaximize', () => {
        mainWindow.webContents.send("w-max", false)
    })
    mainWindow.on('closed', () => {
        mainWindow = null
        app.quit();
    })

    return mainWindow
}

function initWindow() {
    //1.创建主窗体
    createMainWindow()
    //2.注册事件
    messageService.initMessage(mainWindow)
}

setTimeout(() => {
    mainWindow.webContents.send('successChannel', 1)
}, 2000)

export default initWindow
